require 'mime/types'
require 'fileutils'
module Simapse
  module AssetFury
    # This class creates a nice holder for working with the file
    class CurrentFile
      @@tempfiles_path = File.expand_path Simapse::AssetFury.tempfile_path
      #~ @@tempfiles_path =  'test'
      attr_reader :filename, :content_type, :path, :size, :from
        
      def initialize(data)
        @filename = name_file_from_data(data)
        @content_type = content_type_from_data(data)
        @path = write_to_file_and_return_path(data)
        @size = data.respond_to?(:size) ? data.size : File.size(data.path)
        @from = data.path
        data.close
      end
      
      def filename=(name)
        @filename = sanitize(name); old_path = @path
        @path = File.expand_path(File.join(@@tempfiles_path, @filename))
        File.rename(old_path, @path) 
        @filename
      end
      
      def open &block
        File.open(self.path, 'rb') do |f|
          yield(f)
        end
      end
      
    private
      # If File from CGI or System     
      def content_type_from_data(data)
        @content_type = data.respond_to?(:content_type) ?
          data.content_type : MIME::Types.type_for(filename).first.content_type
      end
        
      def name_file_from_data(data)
        @filename = data.respond_to?(:original_filename) ?
          sanitize(data.original_filename) : File.basename(data.path)
      end
    
      #Creates the working file
      def write_to_file_and_return_path(data)
        File.open(File.join(@@tempfiles_path, filename), 'wb') do |f|
          f.write data.read
          File.expand_path f.path
        end
      end
      
      def sanitize(name)
        name
      end
     
      
    end #TmpFile
  end #AssetFury
end #Simapse
#TESTS
#~ FileUtils.mkdir_p('test')
#~ f = Simapse::AssetFury::CurrentFile.new(File.open('test.jpg', 'rb'))
#~ puts f.inspect
#~ f.filename = 'another_test.jpg'
#~ puts f.inspect
